package com.chenl.provider.DEMOS.EasyExcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.ClientAnchorData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.util.FileUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenl.provider.DEMOS.EasyExcel.demo.ImageData;
import com.chenl.provider.DEMOS.设计模式.策略模式.two.AnimalService;
import com.chenl.provider.DTO.ExcelInfo;
import com.chenl.provider.DTO.entity.MyStudent;
import com.chenl.provider.feign.ConFeign;
import com.chenl.provider.mapper.StuMapper;
import com.chenl.provider.util.EasyExcelUtils;
import com.chenl.provider.util.RedisLock;
import com.chenl.provider.util.RedisService;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@RequestMapping("/excel")
@RefreshScope
@Slf4j
public class ExcelTestCon extends ServiceImpl<StuMapper, MyStudent> {
    @Autowired
    AnimalService animalService;
    @Autowired
    ConFeign conFeign;
    @Autowired
    RedisService redisService;
    @Autowired
    StuMapper stuMapper;

    @Autowired
    RedisLock redisLock;
    @Autowired
    RestTemplate restTemplate;

    /**
     * easyExcel导入
     * @param file
     * @throws Exception
     */
    @RequestMapping(value = "/poiTest", method = RequestMethod.POST)
    public void download(@RequestBody MultipartFile file) throws Exception {
        List<ReadSheet> readSheets = EasyExcel.read(file.getInputStream()).build().excelExecutor().sheetList();//获得sheet页,有几页list的size就是几,一般为1
        for (ReadSheet readSheet : readSheets) {//遍历sheet页
            //每一行封装成一个对象,根据表头和实体类属性进行匹配 | 有多少行就能封装成多少个对象,list.size()就是多少
            List<PoiTestVo> list = EasyExcel.read(file.getInputStream())
                    .head(PoiTestVo.class)
                    .sheet(readSheet.getSheetName())//从哪个表拿取,可以用索引也可以用表名,若只有1个表,可以直接填0
                    .doReadSync();
            for (PoiTestVo poiTestVo : list) {
                System.out.println(poiTestVo.getName()+"-"+poiTestVo.getAge()+"-"+poiTestVo.getPhoneNumber());
            }
        }
    }

    /**
     * easyExcel导出模板
     * @throws Exception
     */
    @GetMapping(value = "/exportTemplate/{business}")
    public void exportTemplate(@ApiParam("业务名称") @PathVariable("business") String business) throws Exception {
        try {
            EasyExcelUtils.downloadExcelTemplate(business);
        } catch (IOException e) {
            log.error("下载模板出错!",e);
            throw new RuntimeException(e);
        }
    }

    /**
     * easyExcel测试
     *
     * @throws Exception
     */
    @PostMapping(value = "/exporttest")
    public void export() throws Exception {
        List<ExcelInfo> list = new ArrayList<>();
        ExcelInfo excelInfo = new ExcelInfo();
        excelInfo.setSheetName("测试名称");
        List<List<String>> headerList = new ArrayList<>();
        headerList.add(new ArrayList<String>() {{
            add("姓名");
        }});
        headerList.add(new ArrayList<String>() {{
            add("年龄");
        }});
        headerList.add(new ArrayList<String>() {{
            add("手机号");
        }});
        List<List<Object>> bodyList = new ArrayList<>();
        List<Object> body1 = new ArrayList<>();
        body1.add("张三");
        body1.add("23");
        body1.add("1772088");
        List<Object> body2 = new ArrayList<>();
        body2.add("里斯");
        body2.add("24");
        body2.add("1772099");
        bodyList.add(body1);
        bodyList.add(body2);
        excelInfo.setHeaderList(headerList);
        excelInfo.setBodyList(bodyList);
        list.add(excelInfo);
        EasyExcelUtils.exportListOut("abc", list);
    }



    /**
     * easyExcel测试
     *
     * @throws Exception
     */
    @PostMapping(value = "/export")
    public void test() throws Exception {
        String fileName = "D:\\data\\" + "imageWrite.xlsx";
        //测试用的图片路径
        String imagePath = "D:\\data\\1.png";
        String imagePath2 = "D:\\data\\1.png";
        //数据列表Demo
        List<ImageData> demoDataList = new ArrayList<>();

        ImageData imageData = new ImageData();
        imageData.setName("张三");
        List<String> path1 = new ArrayList<>();
        path1.add(imagePath);
        List<String> url1 = new ArrayList<>();
        url1.add("https://img0.baidu.com/it/u=197359220,4246921900&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666");
//        imageData.setImagePathList(path1);
        imageData.setImageUrlList(url1);

        ImageData imageData2 = new ImageData();
        imageData2.setName("李四");
        List<String> path2 = new ArrayList<>();
        path2.add(imagePath);
        path2.add(imagePath);
        List<String> url2 = new ArrayList<>();
        url2.add("https://img0.baidu.com/it/u=3555616031,19727136&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200");
        url2.add("https://img0.baidu.com/it/u=1221852304,2286922854&fm=253&fmt=auto&app=138&f=JPEG?w=424&h=600");
        url2.add("https://img0.baidu.com/it/u=3043686681,858909288&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889");
//        imageData2.setImagePathList(path2);
        imageData2.setImageUrlList(url2);
        demoDataList.add(imageData);
        demoDataList.add(imageData2);
        this.genImageExcel(demoDataList,"testt");
    }

    /**
     * 生成有图片的excel
     *
     * @param demoDataList 数据列表
     * @param fileName     生成文件路径
     */
    @SneakyThrows
    private void genImageExcel(List<ImageData> demoDataList, String fileName) {
        if (CollectionUtils.isEmpty(demoDataList)) {
            return;
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Access-Control-Expose-Headers", "name");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        response.setHeader("name", fileName + ".xlsx");
        //图片列最大图片数
        AtomicReference<Integer> maxImageSize = new AtomicReference<>(0);
        demoDataList.forEach(item -> {
            if (CollectionUtils.isNotEmpty(item.getImagePathList()) && item.getImagePathList().size() > maxImageSize.get()) {
                maxImageSize.set(item.getImagePathList().size());
            }else if (CollectionUtils.isNotEmpty(item.getImageUrlList()) && item.getImageUrlList().size() > maxImageSize.get()){
                maxImageSize.set(item.getImageUrlList().size());
            }
        });
        //设置列长度所用类
        com.chenl.provider.DEMOS.EasyExcel.demo.AutoColumnWidthStyleStrategy longWidth = new com.chenl.provider.DEMOS.EasyExcel.demo.AutoColumnWidthStyleStrategy();
        demoDataList.forEach(item -> {
            //每张图片间距
            Integer splitWidth = 2;
            //每张图片的长度
            Integer imageWidth = 80;
            //图片列的最大长度
            Integer sumWidth = maxImageSize.get() * (imageWidth + splitWidth);
            WriteCellData<Void> writeCellData = new WriteCellData<>();
            if (CollectionUtils.isNotEmpty(item.getImagePathList())) {
                List<com.alibaba.excel.metadata.data.ImageData> imageDataList = new ArrayList<>();
                List<String> imagePathList = item.getImagePathList();
                for (int i = 1; i <= imagePathList.size(); i++) {
                    String path = imagePathList.get(i - 1);
                    Integer left = imageWidth * (i - 1) + i * splitWidth;
                    Integer right = sumWidth - imageWidth - left;
                    com.alibaba.excel.metadata.data.ImageData imageData = new com.alibaba.excel.metadata.data.ImageData();
                    try {
                        imageData.setImage(FileUtils.readFileToByteArray(new File(path)));
//                        imageData.setImage(com.chenl.provider.util.FileUtils.inputStreamToByte(com.chenl.provider.util.FileUtils.getInputStreamFromUrl("https://tm-image.qichacha.com/f8f1f25fab366739d4bc138ac4852fe8.jpg")));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageData.setImageType(com.alibaba.excel.metadata.data.ImageData.ImageType.PICTURE_TYPE_PNG);
                    //距离单元格顶部距离
                    imageData.setTop(1);
                    //距离单元格底部距离
                    imageData.setBottom(1);
                    //距离单元格左边距离
                    imageData.setLeft(left);
                    //距离单元格右边距离
                    imageData.setRight(right);
                    imageData.setAnchorType(ClientAnchorData.AnchorType.DONT_MOVE_DO_RESIZE);
                    imageDataList.add(imageData);
                }
                writeCellData.setImageDataList(imageDataList);

                Map<String, Integer> zdyColumnWidth = new HashMap<>();
                //图片列名称，对应导出对象的列名称，图片列长度
                zdyColumnWidth.put("图片信息", sumWidth / 6);
                longWidth.setZdyColumnWidth(zdyColumnWidth);
            }
            else if (CollectionUtils.isNotEmpty(item.getImageUrlList())){
                List<com.alibaba.excel.metadata.data.ImageData> imageDataList = new ArrayList<>();
                List<String> imageUrlList = item.getImageUrlList();
                for (int i = 1; i <= imageUrlList.size(); i++) {
                    String url = imageUrlList.get(i - 1);
                    Integer left = imageWidth * (i - 1) + i * splitWidth;
                    Integer right = sumWidth - imageWidth - left;
                    com.alibaba.excel.metadata.data.ImageData imageData = new com.alibaba.excel.metadata.data.ImageData();
                    try {
                        imageData.setImage(com.chenl.provider.util.FileUtils.inputStreamToByte(com.chenl.provider.util.FileUtils.getInputStreamFromUrl(url)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageData.setImageType(com.alibaba.excel.metadata.data.ImageData.ImageType.PICTURE_TYPE_PNG);
                    //距离单元格顶部距离
                    imageData.setTop(1);
                    //距离单元格底部距离
                    imageData.setBottom(1);
                    //距离单元格左边距离
                    imageData.setLeft(left);
                    //距离单元格右边距离
                    imageData.setRight(right);
                    imageData.setAnchorType(ClientAnchorData.AnchorType.DONT_MOVE_DO_RESIZE);
                    imageDataList.add(imageData);
                }
                writeCellData.setImageDataList(imageDataList);

                Map<String, Integer> zdyColumnWidth = new HashMap<>();
                //图片列名称，对应导出对象的列名称，图片列长度
                zdyColumnWidth.put("图片信息", sumWidth / 6);
                longWidth.setZdyColumnWidth(zdyColumnWidth);
            }
            item.setWriteCellDataFile(writeCellData);
        });
        //写入数据
//        EasyExcel.write(fileName, ImageDemoData2.class).registerWriteHandler(longWidth).sheet().doWrite(demoDataList);
        EasyExcel.write(response.getOutputStream(), ImageData.class).registerWriteHandler(longWidth).sheet().doWrite(demoDataList);

    }

    private WriteCellData<Void> buildPathsToWell(List<String> paths) {
        WriteCellData<Void> writeCellData = new WriteCellData<>();
        com.chenl.provider.DEMOS.EasyExcel.demo.AutoColumnWidthStyleStrategy longWidth = new com.chenl.provider.DEMOS.EasyExcel.demo.AutoColumnWidthStyleStrategy();
        if (CollectionUtils.isNotEmpty(paths)) {
            //每张图片间距
            Integer splitWidth = 2;
            //每张图片的长度
            Integer imageWidth = 80;
            //图片列的最大长度
            Integer sumWidth = paths.size() * (imageWidth + splitWidth);

            List<com.alibaba.excel.metadata.data.ImageData> imageDataList = new ArrayList<>();
            List<String> imagePathList = paths;
            for (int i = 1; i <= imagePathList.size(); i++) {
                String path = imagePathList.get(i - 1);
                Integer left = imageWidth * (i - 1) + i * splitWidth;
                Integer right = sumWidth - imageWidth - left;
                com.alibaba.excel.metadata.data.ImageData imageData = new com.alibaba.excel.metadata.data.ImageData();
                try {
                    imageData.setImage(FileUtils.readFileToByteArray(new File(path)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imageData.setImageType(com.alibaba.excel.metadata.data.ImageData.ImageType.PICTURE_TYPE_PNG);
                //距离单元格顶部距离
                imageData.setTop(1);
                //距离单元格底部距离
                imageData.setBottom(1);
                //距离单元格左边距离
                imageData.setLeft(left);
                //距离单元格右边距离
                imageData.setRight(right);
                imageData.setAnchorType(ClientAnchorData.AnchorType.DONT_MOVE_DO_RESIZE);
                imageDataList.add(imageData);
            }
            writeCellData.setImageDataList(imageDataList);

            Map<String, Integer> zdyColumnWidth = new HashMap<>();
//            图片列名称，对应导出对象的列名称，图片列长度
            zdyColumnWidth.put("图片信息", 60);
            longWidth.setZdyColumnWidth(zdyColumnWidth);
        }
        return writeCellData;
    }





}
